package com.retoc.oawx.config.shiro;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class JWTUtil {

    @Value("${oawx.jwt.secret}")
    private String secret;

    @Value("${oawx.jwt.expire}")
    private int expire;

    public String createToken(int userId){
        DateTime offset = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, 5);
        Algorithm algorithm=Algorithm.HMAC256(secret);
        JWTCreator.Builder builder= JWT.create();
        return builder.withClaim("userId",userId).withExpiresAt(offset).sign(algorithm);
    }

    public int getUserId(String token){
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("userId").asInt();
    }

    public void verifierToken(String token) {
        Algorithm algorithm=Algorithm.HMAC256(secret);
        JWTVerifier build = JWT.require(algorithm).build();
        build.verify(token);
    }
}
